<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Cache;
use think\Config;
use think\Validate;
use think\Db;

/**
 * 答题接口
 */
class Dati extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        $this->wechat_db = Db::connect(config('wechat'));
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    public function getsessionkey(){

        $appid = 'wx20ed65cbd26fe73b';
        $secret = 'ea2f5e06c90b9967a4fd9f3e8ae48c2c';

        $code = trim($this->request->post('code'));
        if (!$code) {
            $this->error('非法操作');
        exit();
        }

        if (!$appid || !$secret) {
            $this->error('非法操作');

            exit();
        }
        //保存openid到緩存

        $get_token_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$get_token_url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        curl_close($ch);
        $_SESSION['min_info'] = json_decode($res,true);
        echo $res;
        exit();
    }

    /*
     * 授权失败**/
    public function authlogin(){

        $openid = $this->request->post('openid');
        if (!$openid) {

            $this->error('授权失败!');
            exit();
        }

        $userinfo = $this->wechat_db->table('ims_fighting_user')->where(['openid'=>$openid])->find();

        if (!$userinfo) {

            $data = array();
            $data['weid'] = 21;
            $data['fid'] = 17;
            $data['type'] = 2;
            $data['nickname'] = $_POST['nickname'];
            $data['sex'] = $_POST['gender'];
            $data['openid'] = $openid;
            $data['thumb'] = $_POST['HeadUrl'];
            $data['create_time'] = time();
            $this->wechat_db->table('ims_fighting_user')->insert($data);
            exit();
        }
    }

    public function getUserInfo(){
        $openid = $this->request->get('openid');
        if (!$openid) {
            $this->error('授权失败!', ['status' => 0]);
            exit();
        }

        $userinfo = $this->wechat_db->table('ims_fighting_user')->where(['openid'=>$openid])->find();

        if($userinfo){
            $dtcount = $this->wechat_db->table('ims_fighting')->where(['from_user'=>$openid])->count();
            $number = $this->wechat_db->table('ims_fighting')->where(['from_user'=>$openid,'begin_time'=>['<=',time()],'begin_time'=>['>=',strtotime("-7 days")]])->count();
            $this->success('获取成功!', ['dtnumber' => $dtcount,'number'=>$number]);
        }else{
            $this->error('获取失败!');

        }

    }

    public function getQuestion(){
        $weid = 21;
        $id =  $this->request->post('id');
        $nocache = $this->request->get('nocache');

        $wechat_db = Db::connect(config('wechat'));
        //判断活动是否配置
        $flight_setting = $wechat_db->table('ims_fighting_setting')->where(['id'=>$id])->find();

        if (empty($flight_setting)) {
            echo json_encode(array('status'=>0,'err'=>'非法访问'.__LINE__));
            exit();
        }
        //查看之前是否有未提交的答题（避免意外退出后重复抽题）
        //$re = pdo_fetch("SELECT * FROM " . tablename('fighting') . " WHERE status=0 and `ip`=:ip AND `fid`={$id} order by id desc", array (':ip' => CLIENT_IP ));
        //初始化数据
        $num = 1;
        $questions = [];
        $time = $flight_setting['answertime'];

        $cachearr = Cache::get("question.arr");
        if($cachearr && empty($nocache)){
            $qdata = $cachearr;
        }else{
            //获取题目列表
            $result = $this->wechat_db->table('ims_fighting_question_bank')->where(['sid'=>$id])->select();

            $qdata = array();
            //随机抽取题目
            foreach ($result as $k=>$v){
                $qdata[$v['type']][]=$v;
            }
            Cache::set("question.arr",$qdata);

        }

        foreach ($qdata as $k=>$v){
            $ts[$k] = array_rand($v, $flight_setting['qnum']);
            //打乱题目
            shuffle($ts[$k]);
        }

        foreach ($ts as $t=>$a){
            //处理题目
            if($t==1){

            }
            foreach($a as $k=>$tmp) {
                $questions[$t][$k+1] = $qdata[$t][$tmp];
            }

            foreach ($questions[$t] as $k => $v) {
                $answer = array();
                if(!empty($v['optionA'])){
                    $v['optionA'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionA']);
                    $answer[] = array('code'=>"A",'value'=>trim($v['optionA']));
                }
                if(!empty($v['optionB'])){
                    $v['optionB'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionB']);
                    $answer[] = array('code'=>"B",'value'=>trim($v['optionB']));
                }
                if(!empty($v['optionC'])){
                    $v['optionC'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionC']);
                    $answer[] = array('code'=>"C",'value'=>trim($v['optionC']));
                }
                if(!empty($v['optionD'])){
                    $v['optionD'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionD']);
                    $answer[] = array('code'=>"D",'value'=>trim($v['optionD']));
                }
                if(!empty($v['optionE'])){
                    $v['optionE'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionE']);
                    $answer[] = array('code'=>"E",'value'=>trim($v['optionE']));
                }
                if(!empty($v['optionF'])){
                    $v['optionF'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionF']);
                    $answer[] = array('code'=>"F",'value'=>trim($v['optionF']));
                }

                $option[$t][$v['id']] = $answer;

                //$questions[$t][$k+1]['question'] = trim($v['question']);
            }
        }
        $returndata = json_encode(array('status'=>1,'err'=>'获取成功','flight'=>$flight_setting,'question'=>$questions,'option'=>$option));


        echo $returndata;
    }

    public function getQuestion2(){
        $weid = 21;
        $id =  $this->request->post('id');
        $nocache = $this->request->get('nocache');


        //判断活动是否配置
        $flight_setting = $this->wechat_db->table('ims_fighting_setting')->where(['id'=>$id])->find();

        if (empty($flight_setting)) {
            echo json_encode(array('status'=>0,'err'=>'非法访问'.__LINE__));
            exit();
        }
        //查看之前是否有未提交的答题（避免意外退出后重复抽题）
        //$re = pdo_fetch("SELECT * FROM " . tablename('fighting') . " WHERE status=0 and `ip`=:ip AND `fid`={$id} order by id desc", array (':ip' => CLIENT_IP ));
        //初始化数据
        $num = 1;
        $questions = [];
        $time = $flight_setting['answertime'];
        $cachearr = cache_load("question.arr");
        if($cachearr && empty($nocache)){
            $qdata = $cachearr;
        }else{
            //获取题目列表
            $result = $this->wechat_db->table('ims_fighting_question_bank')->where(['sid'=>$id])->select();
            $qdata = array();
            //随机抽取题目
            foreach ($result as $k=>$v){
                $qdata[$v['type']][]=$v;
            }
            Cache::set("question.arr",$qdata);
        }

        foreach ($qdata as $k=>$v){
            if($k==1){
                $ts[$k] = array_rand($v, 20);
            }else{
                //$ts[$k] = array_rand($v, 3);
            }

            //打乱题目
            shuffle($ts[$k]);
        }

        foreach ($ts as $t=>$a){
            //处理题目
            if($t==1){

            }
            foreach($a as $k=>$tmp) {
                $questions[$t][$k+1] = $qdata[$t][$tmp];
            }

            foreach ($questions[$t] as $k => $v) {
                $answer = array();
                if(!empty($v['optionA'])){
                    $v['optionA'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionA']);
                    $answer[] = array('code'=>"A",'value'=>trim($v['optionA']));
                }
                if(!empty($v['optionB'])){
                    $v['optionB'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionB']);
                    $answer[] = array('code'=>"B",'value'=>trim($v['optionB']));
                }
                if(!empty($v['optionC'])){
                    $v['optionC'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionC']);
                    $answer[] = array('code'=>"C",'value'=>trim($v['optionC']));
                }
                if(!empty($v['optionD'])){
                    $v['optionD'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionD']);
                    $answer[] = array('code'=>"D",'value'=>trim($v['optionD']));
                }
                if(!empty($v['optionE'])){
                    $v['optionE'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionE']);
                    $answer[] = array('code'=>"E",'value'=>trim($v['optionE']));
                }
                if(!empty($v['optionF'])){
                    $v['optionF'] = str_replace(array("\r\n", "\r", "\n"), "", $v['optionF']);
                    $answer[] = array('code'=>"F",'value'=>trim($v['optionF']));
                }

                $option[$t][$v['id']] = $answer;

                //$questions[$t][$k+1]['question'] = trim($v['question']);
            }
        }
        $flight_setting['type'][1]=5;
        //$flight_setting['type'][3]=3;
        $returndata = json_encode(array('status'=>1,'err'=>'获取成功','flight'=>$flight_setting,'question'=>$questions,'option'=>$option));


        echo $returndata;
    }

    public function postScore(){
        $openid = $this->request->post('openid');
        $score = $this->request->post('score');
        $address = $this->request->post('address');
        $nickName = $this->request->post('nickName');
        $longitude = $this->request->post('longitude');
        $latitude = $this->request->post('latitude');
        $weid = 21;
        $id = 17;
        if (!$openid) {
            echo json_encode(array('status' => 0, 'err' => '授权失败！' . __LINE__));
            exit();
        }
        $insert['fid'] = $id;
        $insert['weid'] = $weid;
        $insert['ip'] = CLIENT_IP;
        $insert['begin_time'] = time();
        $insert['score'] = $score;
        $insert['nickName'] = $nickName;
        $insert['address'] = $address;
        $insert['from_user'] = $openid;
        $insert['latitude'] = $latitude;
        $insert['longitude'] = $longitude;
        $this->wechat_db->table('ims_fighting')->insert($insert);

    }

    public function getUserCount(){

        $count = $this->wechat_db->table('ims_fighting')->where(['weid'=>21])->count();

        echo  json_encode(array('status'=>1,'err'=>'获取成功','count'=>$count));
    }
}
